package com.imessage.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 */
public class ExportExcel<T>{
    /**
     * 导入
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> importExcel(String fileName) throws Exception {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            InputStream is = new FileInputStream(fileName);
            XSSFWorkbook XSSFWorkbook = new XSSFWorkbook(is);

            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < XSSFWorkbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet XSSFSheet = XSSFWorkbook.getSheetAt(numSheet);
                if (XSSFSheet == null) {
                    continue;
                }

                // 头部行
                XSSFRow XSSFhead = XSSFSheet.getRow(1);
                if (XSSFhead == null) {
                    continue;
                }
                // 获取当前最后单元格列号
                int lastCellNum = XSSFhead.getLastCellNum();
                String[] arr = new String[lastCellNum];
                for (int j = 0; j < lastCellNum; j++) {
                    Cell cell = XSSFhead.getCell(j);
                    if (cell != null) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String value = cell.getStringCellValue();
                        arr[j] = value;
                    }
                }

                // 循环行Row
                for (int rowNum = 2; rowNum <= XSSFSheet.getLastRowNum(); rowNum++) {
                    // 循环的当前行
                    XSSFRow XSSFRow = XSSFSheet.getRow(rowNum);
                    if (XSSFRow == null) {
                        continue;
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    for (int j = 0; j < lastCellNum; j++) {
                        Cell cell = XSSFRow.getCell(j);

                        if (cell != null) {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            String value = cell.getStringCellValue();
                            map.put(arr[j], value);
                        }

                    }
                    list.add(map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 自定义字段导出
     *
     * @param headers
     * @param dataset
     * @param fileName
     */
    public String exportExcel3(HttpServletRequest request, String[] headers, String[] par,
                               List<Map<String, Object>> dataset, String fileName,Environment environment) {
        String result = "";
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            XSSFCell cell = row.createCell(i);
            XSSFRichTextString text = new XSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        try {
            // 遍历集合数据，产生数据行
            int index = 0;
            for (Map<String, Object> map : dataset) {
                index++;
                row = sheet.createRow(index);
                for (short i = 0; i < headers.length; i++) {
                    XSSFCell cell = row.createCell(i);

                    Object value = map.get(par[i]);

                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    // 其它数据类型都当作字符串简单处理
                    if (value != null && value != "") {
                        textValue = value.toString();
                    }
                    if (textValue != null) {
                        XSSFRichTextString richString = new XSSFRichTextString(textValue);
                        cell.setCellValue(richString);
                    }
                }
            }
            if (0 == index) {
                result = "no";
            } else {
                result = getExportedFile(request, workbook, fileName,environment);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        workbook = null;
        dataset = null;
        System.gc();
        return result;
    }


    /**
     * 方法说明: 指定路径下生成EXCEL文件
     *
     * @return
     */
    public String getExportedFile(HttpServletRequest request, XSSFWorkbook workbook, String name,Environment environment) throws Exception {
        BufferedOutputStream fos = null;
        String savePath=String.format("%s%s", StrUtil.getOsResourceLoc(environment),"img");
        String time = DateUtil.getDate(new Date());//中间目录
        time = time.replaceAll("-", "");

        savePath += File.separator + time;


        File fileDir = new File(savePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String filename = name+new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime()) + ".xlsx";
        try {
            FileOutputStream t = new FileOutputStream(savePath + File.separator + filename);
            fos = new BufferedOutputStream(t);
            workbook.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
        workbook = null;
        return time+File.separator+filename;
    }

}